﻿using System;
using System.Collections.Generic;
using TEngine;
using TMPro;
using UnityEngine;

namespace GameLogic.Localization
{
    [RequireComponent(typeof(TextMeshProUGUI))]
    public class LLocalization : MonoBehaviour
    {
        public string key = "";
        public bool autoFill = true;
        private TextMeshProUGUI _text;
        private bool _autoFill;
        private void Awake()
        {
            _text = GetComponent<TextMeshProUGUI>();
        }

        private void Start()
        {
            _autoFill = autoFill;
            if (_autoFill)
            {
                GameEvent.AddEventListener<LanguageType, LanguageType>(GameEventType.OnChangeLanguage, OnChangeLanguage);
                UpdateText();
            }
        }

        private void OnDestroy()
        {
            if (_autoFill)
            {
                GameEvent.RemoveEventListener<LanguageType, LanguageType>(GameEventType.OnChangeLanguage, OnChangeLanguage);
            }
        }

        private void OnChangeLanguage(LanguageType newLanguage, LanguageType oldLanguage)
        {
            UpdateText();
        }

        public void UpdateText(Dictionary<string, string> param = null)
        {
            _text.text = LLocalizationManager.Instance.GetStringEx(key, param);
        }
    }
}